﻿import { Component, OnInit, Injector, ViewChild, ElementRef, ViewEncapsulation } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LazyLoadEvent } from 'primeng/api';
import { Paginator } from 'primeng/primeng';
import { Table } from 'primeng/table';

import { BatchCostServiceProxy, ComboboxItemDto, CostType } from '@shared/service-proxies/service-proxies';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppWorkshop } from '@shared/AppEnums';

@Component({
    templateUrl: './cost-result.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class CostResultComponent extends AppComponentBase implements OnInit {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('workShopCombobox') workShopCombobox: ElementRef;
    selectedDate = new Date();
    constructor(injector: Injector, private _batchCostServiceProxy: BatchCostServiceProxy) {
        super(injector);
    }

    filterText = '';
    cols: CostType[];
    workShop: number;
    workShopComboboxs = new Array<ComboboxItemDto>();

    ngOnInit(): void {
        this.workShop = AppWorkshop.Machine;
        this.workShopComboboxs = this.getWorkshops();
    }

    getContracts(event?: LazyLoadEvent) {
        this.primengTableHelper.showLoadingIndicator();
        this._batchCostServiceProxy
            .getBatchesCosts(
                this.filterText,
                this.selectedDate.getFullYear(),
                this.selectedDate.getMonth() + 1,
                this.workShop,
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                result.items.forEach(el => {
                    let item = new Object();

                    result.cols.forEach((col, idx) => {
                        item[col.category + col.title] = el.costs[idx];
                    });

                    (el as any).detail = item;
                });

                this.cols = result.cols;
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }
}
